<?php
/**
*PHP SDK for QPlus Push API
*
*@version 1.0.1
*@copyright 2011,Tencent Corporation.All rights reserved.
*/



/**
*如果您的PHP不支持JSON，请升级到PHP5.2.x以上版本
*/
if(!function_exists("json_decode"))
{
	throw new Exception('qplus open API needs the JSON PHP extension.');
}
/**
*如果您的PHP没有安装cURL扩展，请先安装
*/
if(!function_exists("curl_init"))
{
	throw new Exception('qplus open API needs the cURL PHP extension.');
}

/**
*提供访问Q+开放平台OpenAPI的接口
*/
class QPlusPush {
	/**
	**SDK版本号
	*/
	const VERSION = '1.0.1';
	
	/**
	*申请的应用ID
	*/
	private $APPID;
	
	private $app_secret;
	/**
	*qplus OpenAPI服务器域名
	*/
	//private $serverName = 'http://tpns.qq.com/cgi-bin/app_push';
	private $serverName = 'http://113.108.2.35/cgi-bin/app_push';
	
	function __construct($app_id , $app_secret)
	{
		$this->setAppId($app_id);
		$this->setAppSecret($app_secret);
	}
	
	/**
	*设置应用ID
	*/
	public function setAppId($app_id)
	{
		$this->APPID = $app_id;
	}
	
	/**
	*获取应用ID
	*/
	public function getAppId()
	{
		return $this->APPID;
	}

	/**
	*设置应用app_ecret
	*/
	public function setAppSecret($app_secret)
	{
		$this->app_secret = $app_secret;
	}
	
	/**
	*获取应用app_ecret
	*/
	public function getAppSecret()
	{
		return $this->app_secret;
	}
	
	/**
	*获取签名信息
	*/
	private function getIdentifyString($para)
	{
		return hash_hmac("sha1" ,  $para  , $this->app_secret . "&");
	}
	
	/**
	 *获取唯一整数
	 */
	
	private function getNonce()
	{
		list($usec,$sec) = explode(" " , microtime());
		return((float)$usec+(float)$sec)*10000;
	}
	
	/**
	*向Q+后台push信息
	*@param string $qplusId
	*@param string $instanceId
	*@param string $push_string
	*@param string $pushmsgid
	*/
	public function push($params)
	{
		$result = "";
		
		//增加三个参数		
		$params["APPID"] = $this->APPID;
		$params["NONCE"] = $this->getNonce();//随机八位数
		$params["TIME"] = time();
		ksort($params);

		//获取加密串
		foreach ($params as $key => $value)
		{
			$result .= "&" .$key . '=' .$value;
		}		
		$result = substr($result , 1 ,strlen($result)-1);		

		//获取签名
		$sig = $this->getIdentifyString("app_push&" . $result);

		//获取url
		$url = $this->serverName . "?" .http_build_query($params). "&IDENTIFYSTRING=" . $sig;
		echo($url);
		//发送请求
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		$content = curl_exec($ch);
		$json = json_decode($content);
		
		return $json;
	}	
}
?>
